package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentSubject;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发布评论
    public void saveComments(String subjectId, String comment,CommentSubject commentSubject) {
        //1、获取操作用户id
        Long userId = UserHolder.getUserId();
        //2、构造Comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(subjectId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);

        //3、调用API保存评论
        Integer commentCount = commentApi.save(comment1,commentSubject);
        log.info("commentCount = " + commentCount);
    }

    //分页查询评论列表
    public PageResult findComments(String subjectId, Integer page, Integer pagesize) {
        //1、调用API查询评论列表
        List<Comment> list = commentApi.findComments(subjectId,CommentType.COMMENT,page,pagesize);
        //2、判断list集合是否存在
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4、构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if(userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                String key = Constants.MOVEMENTS_INTERACT_KEY + comment.getId().toHexString();
                //是否点赞
                String isLikehashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
                if(redisTemplate.opsForHash().hasKey(key,isLikehashKey)) {
                    vo.setHasLiked(1);
                }
                vos.add(vo);
            }
        }
        //5、构造返回值
        return new PageResult(page,pagesize,0L,vos);
    }


    public Integer disposeComment(String subjectId, boolean isFront, CommentType commentType, CommentSubject commentSubject) {
        //1、调用API查询用户是否已点赞/是否已喜欢
        Boolean hasComment = commentApi.hasComment(subjectId,UserHolder.getUserId(),commentType);
        //2.1、如果已经点赞/已喜欢，抛出异常
        if(hasComment && isFront) {
            if(commentType.getType() == 1){
                throw new BusinessException(ErrorResult.likeError());
            }else{
                throw new BusinessException(ErrorResult.loveError());
            }
        //2.2、如果未点赞/未喜欢，抛出异常
        }else if(!hasComment && !isFront) {
            if(commentType.getType() == 1){
                throw new BusinessException(ErrorResult.disLikeError());
            }else{
                throw new BusinessException(ErrorResult.disloveError());
            }
        }
        //3、组装comment数据，进行保存或者删除
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(subjectId));
        comment.setCommentType(commentType.getType());
        comment.setUserId(UserHolder.getUserId());

        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + subjectId;
        String hashKey = "";
        if(commentType.getType() == 1){
            hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        }else {
            hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        }
        Integer count;
        if(isFront){
            comment.setCreated(System.currentTimeMillis());
            count = commentApi.save(comment,commentSubject);
            redisTemplate.opsForHash().put(key,hashKey,"1");
        }else{
            count = commentApi.delete(comment,commentSubject);
            redisTemplate.opsForHash().delete(key,hashKey);
        }
        return count;
    }
}
